package org.dragonnova.iot.business.cloud.transport.adapter;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandler.Sharable;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelOutboundHandlerAdapter;
import io.netty.channel.ChannelPromise;
import io.netty.util.ReferenceCountUtil;

import org.dragonnova.iot.business.cloud.statistics.MessageProcessor;
import org.dragonnova.iot.business.cloud.transport.ParseException;
import org.dragonnova.iot.business.cloud.transport.model.Packet;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

@Sharable
public final class TagEncoderAdapter extends ChannelOutboundHandlerAdapter {
	private final static Logger LOGGER = LoggerFactory
			.getLogger(TagEncoderAdapter.class);

	@Autowired
	private MessageProcessor messageProcessor;

	@Override
	public void write(ChannelHandlerContext ctx, Object msg,
			ChannelPromise promise) throws Exception {

		try {
			if (msg instanceof Packet) {
				ByteBuf bb = ((Packet) msg).encode();
				ctx.writeAndFlush(bb);
				messageProcessor.putUpFlow(1.0 * bb.readableBytes());
			} else {
				ctx.writeAndFlush(msg);
			}
		} catch (ParseException e) {
			e.printStackTrace();
		} finally {
			ReferenceCountUtil.release(msg);
		}
	}
}
